var supplierObj = [];
var limit = 15;
var tid;
var orgObj = convertOrgToObj(orgList);
var suppObj = convertEnumToObj(supplierTypeList);

layui.use(['laypage', 'table', 'form'], function(){
    var table = layui.table;
    var form = layui.form;

    var verifyQrcode = false;

    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'name', title: '简称', width:280,  align: 'center'}
            ,{field: 'fullName', title: '全称', width:280,  align: 'center'}
            ,{field: 'legal', title: '法人代表', width:100, align: 'center'}
            ,{field: 'phone', title: '联系方式', width:140, align: 'center'}
            ,{field: 'linkMan', title: '联系人', width:100, align: 'center'}
            ,{field: 'orgName', title: '公司名称', width:140, align: 'center'}
            ,{field: 'taxCode', title: '纳税人识别号', width: 200, align: 'center'}
            ,{field: 'type', title: '类型', width: 90, align: 'center',templet:function (val) {
                return suppObj[val.type];
            }}
            ,{field: 'address', title: '联系地址', width:260, align: 'center'}
            ,{field: 'status', title: '状态', width:80, align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'remark', title: '备注', width: 300, align: 'center'}
            ,{field: 'createTime', title: '创建时间', width: 200, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 200, align:'center', templet:function (val) {
                var str = '<a lay-event="detail" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-primary">详情</a>';
                if (val.status == 0)
                    str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">禁用</a>';
                else
                    str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-normal">启用</a>';
                str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">编辑</a>';
                return str;
            }}
        ]
    ];

    table.render({
        elem: '#body-list'
        ,url: '/mainsupplier/page'
        ,method: 'post'
        ,page: true
        ,contentType: 'application/json'
        ,cols: todoCols
        ,limit: limit
        ,limits: [15,30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit,
            orgId:$('.search-origin').val(),
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res);
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"

        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){
            var id = data.id;
            var status = data.status;
            var tip = '是否要启用？';
            if (status == 0)
                tip = '是否要删除？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option =  '{"id": '+id+', "status":'+updateStatus+'}';
                save(option, "/mainsupplier/updatestatus/");
            }, function(index){

            });
        } else if(layEvent === 'edit'){
            tid = data.id;
            $('#update-mainsupplier-body').show();
            $('#update-mainsupplier-body .update-name').val(data.name);
            $('#update-mainsupplier-body .update-fullName').val(data.fullName);
            $('#update-mainsupplier-body .update-legal').val(data.legal);
            $('#update-mainsupplier-body .update-phone').val(data.phone);
            $('#update-mainsupplier-body .update-linkMan').val(data.linkMan);
            $('#update-mainsupplier-body .update-origin').val(data.orgId);
            $('#update-mainsupplier-body .update-taxCode').val(data.taxCode);
            $('#update-mainsupplier-body .update-type').val(data.type);
            $('#update-mainsupplier-body .update-address').val(data.address);
            $('#update-mainsupplier-body .remark').val(data.remark);
            $("#updateBtn").show();
            form.render();
        } else  if(layEvent === 'detail'){
            $("#updateTitle").text("查看供应商数据");
            $('#update-mainsupplier-body').show();
            $('#update-mainsupplier-body .update-name').val(data.name);
            $('#update-mainsupplier-body .update-fullName').val(data.fullName);
            $('#update-mainsupplier-body .update-legal').val(data.legal);
            $('#update-mainsupplier-body .update-phone').val(data.phone);
            $('#update-mainsupplier-body .update-linkMan').val(data.linkMan);
            $('#update-mainsupplier-body .update-origin').val(data.orgId);
            $('#update-mainsupplier-body .update-taxCode').val(data.taxCode);
            $('#update-mainsupplier-body .update-type').val(data.type);
            $('#update-mainsupplier-body .update-address').val(data.address);
            $('#update-mainsupplier-body .remark').val(data.remark);
            var text = data.id + ","+data.name + ","+data.taxCode;
            var config = {
                width:200,
                height:200,
                text: text
            }
            if(!verifyQrcode){
                $(".qrcode").qrcode(config);
                verifyQrcode = true;
            }
            $(".qrcode-show").show();
            $("#updateBtn").hide();
            form.render();
        }
    });

    form.on('select(search-status)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-origin)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-type)', function(data) {
        $(".btn-query").trigger("click");
    });
    $('.btn-query').on('click', function () {//搜索按钮
        var searchVal = $('.search-text').val();
        var status = $('.search-status').val();
        var orgId = $('.search-origin').val();
        var type = $('.search-type').val();

        var option = {page:1,limit:limit};
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(type))
            option['type'] = type;
        if (!isNull(orgId))
            option['orgId'] = orgId;
        if (!isNull(status))
            option['status'] = status;
        table.reload('body-list', {
            where: option
        });
    });

    $("#update-mainsupplier-body .close").on("click", function() {
        $("#update-mainsupplier-body").hide();
        $("#update-mainsupplier-body input").val("");
        $("#update-mainsupplier-body select").val("");
        $("#update-mainsupplier-body textarea").val("");
        $(".qrcode-show").hide();
        form.render();
        tid = -1;
    });
    form.on('submit(updateBtns)', function() {
        var orgName = $.trim($("#update-mainsupplier-body .update-origin").find("option:selected").text());//公司
        var orgId = $.trim($("#update-mainsupplier-body .update-origin").val());//公司
        var remark = $.trim($("#update-mainsupplier-body .remark").val());//备注
        var name = $.trim($("#update-mainsupplier-body .update-name").val());//
        var fullName = $.trim($("#update-mainsupplier-body .update-fullName").val());//
        var legal = $.trim($("#update-mainsupplier-body .update-legal").val());//
        var phone = $.trim($("#update-mainsupplier-body .update-phone").val());//
        var linkMan = $.trim($("#update-mainsupplier-body .update-linkMan").val());//
        var type = $.trim($("#update-mainsupplier-body .update-type").val());//
        var address = $.trim($("#update-mainsupplier-body .update-address").val());//
        var taxCode = $.trim($("#update-mainsupplier-body .update-taxCode").val());//
        var options =  '{"id": '+tid+', "orgName":"'+orgName+'", "orgId":'+orgId+', "remark":"'+remark+'", "name":"'+name+'"' +
            ',"fullName":"'+fullName+'", "legal":"'+legal+'", "phone":"'+phone+'", "linkMan":"'+linkMan+'", "type":'+type+'' +
            ', "address":"'+address+'", "taxCode":"'+taxCode+'"}';
        if (isNull(tid) || tid == -1) {
            layer.msg("获取修改信息错误,请刷新再试！");
            return ;
        }
        save(options, "/mainsupplier/update");
    });


    function save(option, url) {//新增或修改
        var loading = layer.load(1);
        console.log(option);
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            data: option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    layer.msg("更新成功!");
                    table.reload('body-list', { where: {offset:0,curr:1,
                            limit: limit,
                            orgId:$('.search-origin').val() }});
                    $("#update-mainsupplier-body").hide();
                    $("#update-mainsupplier-body input").val("");
                    $("#update-mainsupplier-body select").val("");
                    $("#update-mainsupplier-body textarea").val("");
                    $(".qrcode-show").hide();
                    form.render();
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }
});